package person.bing.fbcloud.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 下一个排列
 * @author: mengfanbing
 * @date: 2020/10/12 10:01
 */
public class Q31 {
    public static void main(String[] args) {
        int[] nums = {1,3,2};
        nextPermutation(nums);
        System.out.println(Arrays.toString(nums));
    }

    public static void nextPermutation(int[] nums) {
        if (nums == null){
            return;
        }
        int length = nums.length;
        if (length <= 1){
            return;
        }
        Integer[] temp = new Integer[length];
        for (int i=0;i<length;i++){
            temp[i] = nums[i];
        }
        //如果是最大排列，返回最小排列
        Arrays.sort(temp, Collections.reverseOrder());
        int[] tempInt = new int[length];
        for (int i=0;i<length;i++){
            tempInt[i] = temp[i];
        }
        if (Arrays.equals(tempInt,nums)){
            Arrays.sort(temp);
            for (int i=0;i<length;i++){
                nums[i] = temp[i];
            }
            return;
        }
        Integer max = nums[length-1];
        List<Integer> tempList = new ArrayList<>();
        //返回下一个更大排列
        for (int i=length-1;i>=0;i--){
            int cur = nums[i];
            if (cur < max){
                Integer betterNum = tempList.stream()
                        .filter(integer -> integer > cur)
                        .sorted()
                        .collect(Collectors.toList())
                        .get(0);
                nums[i] = betterNum;
                tempList.remove(betterNum);
                tempList.add(cur);
                List<Integer> tempListSorted = tempList.stream().sorted().collect(Collectors.toList());
                int z=0;
                for (int j=i+1;j<length;j++){
                    nums[j] = tempListSorted.get(z++);
                }
                return;
            }else {
                max = cur;
                tempList.add(cur);
            }
        }
    }
}
